#include "mapchunk.h"
#include "configuration.h"
#include "map.h"
#include "image/image.h"

QHash<QString, MapChunk*> MapChunk::chunks;
QList<QString> MapChunk::usage_stack;

const MapChunk* MapChunk::getChunk( int x, int y, int z, const QString& map_id)
{
    QString chunk_id = QString("%1 %2 %3 %4").arg( map_id )
                                             .arg(x)
                                             .arg(y)
                                             .arg(z);


    MapChunk* found = chunks.value( chunk_id, NULL );
    if ( !found )
    {   // Chunk not found? Load it...

        // But first make some space for it, if we already loaded the maximum number of chunks...
        if ( chunks.count() >= MAX_CHUNKS )
        {
            // The oldest used chunk is the first chunk of the list:
            QString oldest_id = usage_stack.takeFirst();
            // delete the chunk
            delete chunks.take( oldest_id );
        }
        // Create new chunk...
        found = new MapChunk( x, y, z, map_id );
        chunks.insert( chunk_id, found );
    }
    else
    {
        // Just find and remove the chunk from the usage stack:
        usage_stack.takeAt( usage_stack.indexOf( chunk_id ) );
    }
    // Add the chunk_id again to the END of the usage stack...
    usage_stack.append( chunk_id );
    return found;
}

MapChunk::MapChunk(int chunk_x, int chunk_y, int zoom, const QString& map_id) :
    QImage()
{
    _chunkValid = false;
    QString path = configuration->defaultPath() +
                   "/map_storage/" +
                   map_id +
                   "/" +
                   QString("%1_%2_%3.ftc").arg(zoom).arg(chunk_x).arg(chunk_y);

    if ( load(path) )
        _chunkValid = true;
    else
        load( ":/misc/cancel.png", "png" );
}

bool MapChunk::chunkValid() const
{
    return _chunkValid;
}
